package com.zrc.japktool.ui;

import com.zrc.japktool.apk.zipalignsign.Apk4kAligner;
import com.zrc.japktool.apk.zipalignsign.zipalign.ZipAlign;
import com.zrc.japktool.ui.view.RichTextFXLogView;
import com.zrc.japktool.util.DialogUtil;
import com.zrc.japktool.util.TaskLog;
import com.zrc.japktool.apk.zipalignsign.ApkSign;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;
import java.nio.file.Paths;
import java.util.List;

public class Tab1Controller_ApkSign {
    private boolean isRunner = false;
    @FXML
    private TextField apkPath_TextField;
    @FXML
    private TextField keyStore_TextField;
    @FXML
    private TextField inputAlias_TextField;
    @FXML
    private TextField inputKsPass_TextField;
    @FXML
    private TextField inputKeyPass_TextField;
    @FXML
    private VBox rootVBox;
    @FXML
    private Button selectApkSignFile_Button;
    @FXML
    private CheckBox quickSign_CheckBox;
    @FXML
    private RichTextFXLogView logView;
    private TaskLog log = new TaskLog() {

        @Override
        public void info(String msg) {logView.info(msg);}

        @Override
        public void warn(String msg) {logView.warn(msg);}

        @Override
        public void debug(String msg) {logView.debug(msg);}

        @Override
        public void error(String msg) {logView.error(msg);}

        @Override
        public void tip(String msg) {logView.tip(msg);}

    };

    @FXML
    public void initialize() {
        logView.tip("等待操作...");// 初始化日志区域
        setupDragAndDrop();// 设置拖放事件处理器
    }

    private void setupDragAndDrop() {
        rootVBox.setOnDragOver(event -> {
            Dragboard db = event.getDragboard();
            if (db.hasFiles()) {
                // 检查文件扩展名
                boolean hasValidFile = db.getFiles().stream()
                        .anyMatch(file -> file.getName().toLowerCase().endsWith(".apk"));
                if (hasValidFile) {
                    event.acceptTransferModes(TransferMode.COPY);
                }
            }
            event.consume();
        });

        rootVBox.setOnDragDropped(event -> {
            Dragboard db = event.getDragboard();
            boolean success = false;
            if (db.hasFiles()) {
                List<File> files = db.getFiles();
                // 只处理第一个有效的APK/XAPK文件
                for (File file : files) {
                    String fileName = file.getName().toLowerCase();
                    String filePath = file.getAbsolutePath().replace("\\", "/");
                    if (fileName.endsWith(".apk")) {
                        apkPath_TextField.setText(filePath);
                        logView.tip("拖放文件: " + filePath);
                        success = true;
                        break;
                    }
                }
            }
            event.setDropCompleted(success);
            event.consume();
        });
    }

    @FXML
    private void selectApkFile() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择APK文件");
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("APK Files", "*.apk"));

        // 设置初始目录为桌面
        File desktopDir = new File(System.getProperty("user.home"), "Desktop");
        if (desktopDir.exists()) {
            fileChooser.setInitialDirectory(desktopDir);
        } else {
            // 如果桌面目录不存在，回退到用户主目录（如 Linux 可能没有 "Desktop" 文件夹）
            fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        }

        File selectedFile = fileChooser.showOpenDialog(null);
        if (selectedFile != null) {
            String filePath = selectedFile.getAbsolutePath().replace("\\", "/");
            apkPath_TextField.setText(filePath);
            logView.tip("已选择APK: " + filePath);
        } else {
            logView.tip("APK选择取消");
        }
    }

    @FXML
    private void selectApkSignFile() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择APK签名文件");
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("APK Signature File", "*.jks", "*.keystore"));

        // 设置初始目录为桌面
        File desktopDir = new File(System.getProperty("user.home"), "Desktop");
        if (desktopDir.exists()) {
            fileChooser.setInitialDirectory(desktopDir);
        } else {
            // 如果桌面目录不存在，回退到用户主目录（如 Linux 可能没有 "Desktop" 文件夹）
            fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        }

        File selectedFile = fileChooser.showOpenDialog(null);
        if (selectedFile != null) {
            String filePath = selectedFile.getAbsolutePath().replace("\\", "/");
            keyStore_TextField.setText(filePath);
            logView.tip("已选择APK签名文件: " + filePath);
        } else {
            logView.tip("选择APK签名文件取消");
        }
    }

    @FXML
    private void handleQuickSignChange(ActionEvent actionEvent) {
        // 1. 获取事件源（快签复选框）及选中状态
        CheckBox quickSignBox = (CheckBox) actionEvent.getSource();
        boolean isQuickSignEnabled = quickSignBox.isSelected(); // 快签是否启用

        // 2. 控制签名相关输入框：不可编辑 + 完全禁用（无法聚焦/点击）
        keyStore_TextField.setEditable(!isQuickSignEnabled);
        inputAlias_TextField.setEditable(!isQuickSignEnabled);
        inputKsPass_TextField.setEditable(!isQuickSignEnabled);
        inputKeyPass_TextField.setEditable(!isQuickSignEnabled);

        keyStore_TextField.setDisable(isQuickSignEnabled);
        inputAlias_TextField.setDisable(isQuickSignEnabled);
        inputKsPass_TextField.setDisable(isQuickSignEnabled);
        inputKeyPass_TextField.setDisable(isQuickSignEnabled);
        selectApkSignFile_Button.setDisable(isQuickSignEnabled);

        if (isQuickSignEnabled) {
            logView.tip("快签模式：签名信息不可编辑...");
        } else {
            logView.tip("文件签名模式：签名信息可编辑...");
        }
    }

    @FXML
    private void startTask() {
        if (isRunner) {
            DialogUtil.showInfoDialog((Stage)logView.getScene().getWindow(),"温馨提示！","当前任务正在进行: 请认真等待...");
            logView.error("当前任务正在进行: 请认真等待...");
            return;
        }

        String apkPath = apkPath_TextField.getText();
        String outputDir = new File(apkPath).getParent();
        if (apkPath.isEmpty()) {
            logView.error("错误: 请先选择APK文件...");
            return;
        }

        if (!quickSign_CheckBox.isSelected()) {//选择文件签名
            String keyStorePath = keyStore_TextField.getText();
            if (keyStorePath.isEmpty()) {
                logView.error("错误: 请先选择签名文件...");
                return;
            }

            String inputAlias = inputAlias_TextField.getText();
            if (inputAlias.isEmpty()) {
                logView.error("错误: 请先输入Alias...");
                return;
            }

            String inputKsPass = inputKsPass_TextField.getText();
            if (inputKsPass.isEmpty()) {
                logView.error("错误: 请先输入ks-pass...");
                return;
            }

            String inputKeyPass = inputKeyPass_TextField.getText();
            if (inputKeyPass.isEmpty()) {
                logView.error("错误: 输入key-pass...");
                return;
            }
        }

        // 创建一个Task来执行耗时操作
        Task<Void> task = new Task<>() {
            @Override
            protected Void call() {
                isRunner = true;
                logView.clear();
                try {
                    String apkNamme = new File(apkPath).getName().replace(".apk", "");
                    String ziplan_inApkPath = apkPath;
                    File ziplan_outApkFile = new File(outputDir, apkNamme + "-zipalign.apk");
                    String ziplan_outApkPath = ziplan_outApkFile.getAbsolutePath().replace("\\", "/");

                    Apk4kAligner apk4kAligner = new Apk4kAligner(log);
                    apk4kAligner.zipAlign(ziplan_inApkPath, ziplan_outApkPath, false);
                    //ApkZipalign.alignApk(ziplan_inApkPath, ziplan_outApkPath, taskLog);
                    //ApkZiplan.zipAlign(Paths.get(ziplan_inApkPath), Paths.get(ziplan_outApkPath), false, Tab1Controller.this::log);
                    //ZipAlign.zipAlign(ziplan_inApkPath, ziplan_outApkPath,log);

                    String sign_inApkPath = ziplan_outApkPath;
                    String sign_outApkPath = new File(outputDir, apkNamme + "-zipalign-sign.apk").getAbsolutePath();
                    if (!quickSign_CheckBox.isSelected()) {//选择文件签名
                        ApkSign apkSign = new ApkSign(log);
                        apkSign.sign(Paths.get(keyStore_TextField.getText()),
                                inputKsPass_TextField.getText(),
                                inputAlias_TextField.getText(),
                                inputKeyPass_TextField.getText(),
                                false,
                                Paths.get(sign_inApkPath),
                                Paths.get(sign_outApkPath));
                    } else {
                        ApkSign apkSign = new ApkSign(log);
                        //apkSign.sign("android", "androiddebugkey", "android", false, Paths.get(sign_inApkPath), Paths.get(sign_outApkPath));
                        apkSign.sign1("123456", "key0", "123456", false, Paths.get(sign_inApkPath), Paths.get(sign_outApkPath));
                    }
                    if (ziplan_outApkFile.exists()) {
                        ziplan_outApkFile.delete();
                        logView.info("apk签名: " + "清理apk对齐缓存...");
                    }
                } catch (Exception e) {
                    log.error(e.getMessage());
                    throw new RuntimeException(e);
                }
                isRunner = false;
                return null;
            }
        };

        // 设置任务失败时的处理
        task.setOnFailed(event -> {
            isRunner = false;
            Throwable exception = task.getException();
            Platform.runLater(() -> {
                logView.error("任务执行失败: " + exception.getMessage());
                exception.printStackTrace();
            });
        });

        // 启动后台线程执行任务
        new Thread(task).start();
    }

}